package org.example.chapter7.service.impl;

import org.example.chapter7.dao.UserDao;
import org.example.chapter7.pojo.User;
import org.example.chapter7.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author CoderXshuai
 * @date 2020/8/1/0001 22:32
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    /**
     * 获取id,取参数id缓存用户
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    @Cacheable(value = "redisCache", key = "'redis_user_'+#id")
    public User getUser(Long id) {
        return userDao.getUser(id);
    }

    /**
     * 插入用户,最后MyBatis会回填id,取结果id缓存用户
     *
     * @param user
     * @return
     */
    @Override
    @Transactional
    @CachePut(value = "redisCache", key = "'redis_user_'+#result.id")
    public User insertUser(User user) {
        userDao.insertUser(user);
        return user;
    }

    /**
     * @param id
     * @param userName
     * @return
     */
    @Override
    @Transactional
    @CachePut(value = "redisCache", key = "'redis_user_'+#id", condition = "#result!='null'")
    public User updateUserName(Long id, String userName) {
        //此处调用getUser方法,该方法缓存注解失效,所以这里还会执行SQL,将查询到数据库最新数据
        User user = this.getUser(id);
        if (user != null) {
            user.setUserName(userName);
            userDao.updateUser(user);
            return user;
        }
        return null;
    }

    @Override
    public int updateUser(User user) {
        return 0;
    }

    /**
     * 命中率低,所以不采用缓存机制
     *
     * @param userName
     * @param note
     * @return
     */
    @Override
    @Transactional
    public List<User> findUsers(String userName, String note) {
        List<User> userList = userDao.findUsers(userName, note);
        return userList;

    }

    /**
     * 移除缓存
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    @CacheEvict(value = "redisCache", key = "'redis_user_'+#id")
    public int deleteUser(Long id) {
        return userDao.deleteUser(id);
    }
}
